package NetWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyTCPServer {
    //创建一个socket关键字
    private ServerSocket serverSocket = null;
    //构造方法
    public MyTCPServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        //使用线程池来避免只能接收一个客户端链接
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("服务器启动！");
        //使用socket关键字来接收一个服务器收到的客户端链接
        //使用while循环去链接客户端
        while (true) {
            Socket clientSocket = serverSocket.accept();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processClient(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    //处理数据
    private void processClient(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线！\n",clientSocket.getInetAddress().toString(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //将字节流变成字符流方便处理数据
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);

            while (true) {
                //判断是否读取完客户端发送的请求
                if (!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //接收请求
                String request = scanner.next();
                //处理请求
                String respond = process(request);
                //将响应返回给客户端
                printWriter.println(respond);
                printWriter.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //最后关闭文件资源
            clientSocket.close();
        }
    }
    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        MyTCPServer myTCPServer = new MyTCPServer(6666);
        myTCPServer.start();
    }
}
